import { Injectable } from '@angular/core';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/toPromise';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { User } from './user.service';
import { ConfigService } from '../../core/common/config.service';
@Injectable()
export class AuthService {
  service = 'TokenService';
  constructor(private user: User, public http: Http, private router: Router, private config: ConfigService) {
  }
  login(value: any): Promise<any> {
    const method = 'getToken';
    const url = this.config.get('url') + '?service=' + this.service + '&method=' + method;
    return this.http.post(url, value).toPromise().then((resp: Response) => {
      const result = resp.json();
      let initResult = true;
      if (result.code === '0000') {
        initResult = this.user.init(result.info);
      }
      result.initResult = initResult;
      return result;
    });
  }
  logout(): void {
    const method = 'destoryToken';
    const url = this.config.get('url') + '?service=' + this.service + '&method=' + method;
    const token = window.sessionStorage.getItem('token');
    this.http.post(url, { userID: this.user.userID, token: token }).toPromise().then((resp: Response) => {
      const result = resp.json();
      if (result.code === '0000') {
        this.user.destroy();
        this.router.navigate(['/login']);
      }
    });
  }
  checkLogin(url: string): Promise<boolean> {
    return this.user.isLoggedIn().then((data: boolean) => {
      if (!data) {
        this.router.navigate(['/login']);
      }
      return data;
    });
  }
}
